package com.example.yiwei.crm.view.activity.customerActivity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.customerDao;
import com.example.yiwei.crm.dao_impl.customerDaoImpl;
import com.example.yiwei.crm.data.GetContact;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.data.GetPersonnal;
import com.example.yiwei.crm.entity.ContactMessageEntity;
import com.example.yiwei.crm.entity.CustomerMessageEntity;
import com.example.yiwei.crm.entity.personnalEntity;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.view.Class.listviewClass.AutoListView;
import com.example.yiwei.crm.view.Class.listviewClass.ListViewAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class SimpleReceiveCustomerActivity extends AppCompatActivity implements AutoListView.OnRefreshListener,AutoListView.OnLoadListener{
//TextView txt_name,txt_disease_category,txt_department,txt_state;
    private AutoListView lstv;
    private ListViewAdapter ladapter;
    CustomerMessageEntity customer;
    List<CustomerMessageEntity> customerlist;
    private ImageView img_commit,img_back;
    personnalEntity personnal;
    boolean tag = false;
    int page = 1;
    String result;
    List<CustomerMessageEntity> customerList;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            List<CustomerMessageEntity> result = (List<CustomerMessageEntity>) msg.obj;
            switch (msg.what) {
                case AutoListView.REFRESH:
                    lstv.onRefreshComplete();
                    customerList.clear();
                    customerList.addAll(result);
                    break;
                case AutoListView.LOAD:
                    lstv.onLoadComplete();
//                    List<CustomerMessageEntity> list = new ArrayList<>();
//                    list.addAll(customerList);
//                    customerList.clear();
                    customerList.addAll(result);
//                    customerList.addAll(list);

                    break;
            }
//            ladapter = new ListViewAdapter(SimpleReceiveCustomerActivity.this,customerList);
//            lstv.setAdapter(ladapter);
//            lstv.setResultSize(result.size());
            ladapter.notifyDataSetChanged();




        }

        ;
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_customer);
        img_back= (ImageView) findViewById(R.id.receive_customer_img_back);
        img_commit= (ImageView) findViewById(R.id.receive_customer_img_commit);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        lstv= (AutoListView) findViewById(R.id.receive_customer_listview);
        lstv.setDivider(new ColorDrawable(Color.rgb(216, 216, 216)));
        lstv.setDividerHeight(1);
        lstv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                customerDao customerDao=new customerDaoImpl();
                customerList=customerDao.querySimpleReceiveCustomerMessage(baseClass.query_all_receive_customer+1,null);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        lstv.setOnRefreshListener(SimpleReceiveCustomerActivity.this);
                        lstv.setOnLoadListener(SimpleReceiveCustomerActivity.this);
                        ladapter = new ListViewAdapter(SimpleReceiveCustomerActivity.this,customerList);

                        lstv.setAdapter(ladapter);
                        ladapter.notifyDataSetChanged();
                        loadData(AutoListView.LOAD);
                        loadData(AutoListView.REFRESH);
                    }
                });
            }
        }).start();


        lstv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final int client_id = customerList.get(i-1).getClient_id();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        customerDao customerdao=new customerDaoImpl();
                        GetCustumer.create();
                        GetCustumer.customers=customerdao.queryDetailedReceiveCustomerMessage(baseClass.query_detailed_receive_customer_url+client_id,null);
                        if ("success".equals(GetCustumer.customers.getTag())) {
                            List<ContactMessageEntity> contacts = customerdao.queryContactAllMessage(baseClass.find_all_contact + client_id, null);
                            for (int i = 0; i < contacts.size(); i++) {
                                if (1 == contacts.get(i).getIs_first_contact()) {
                                    GetContact.create();
                                    GetContact.contact = contacts.get(i);
                                    tag = true;
                                }
                            }
                            if (contacts.size() == 0 || !tag) {
                                GetContact.create();
                            }
                            tag = false;
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SimpleReceiveCustomerActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent=new Intent(SimpleReceiveCustomerActivity.this,CustomerDetailedMessageActivity.class);
                                intent.putExtra("number",client_id);
                                intent.putExtra("tag","lqkh");
                                startActivity(intent);
                            }
                        });
                    }
                }).start();
            }
        });
        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final List<Integer> list = ListViewAdapter.getIDs();
                        for (int i=0;i<list.size();i++){
                            int customer_id=list.get(i);
                            JSONObject object=new JSONObject();
                            try {
                                personnal= GetPersonnal.get();
                                int personnal_id=personnal.getPersonnal_id();
                                object.put("KAA28",personnal_id);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String str=object.toString();
                            result= NetWorkUtils.getCount(baseClass.receive_customer_url+customer_id,str);
                        }
                        try {
                            JSONObject object1=new JSONObject(result);
                            String boolen=object1.getString("boolean");
                            if ("error".equals(boolen)){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(SimpleReceiveCustomerActivity.this, "未领取成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }else if ("success".equals(boolen)){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ListViewAdapter.setState();
                                        for (int i=0;i<list.size();i++){
                                            for (int j=0;j<customerList.size();j++){
                                                if (list.get(i)==customerList.get(j).getClient_id()){
                                                    customerList.remove(customerList.get(j));
                                                }
                                            }
                                        }
                                        ladapter.notifyDataSetChanged();
                                        Toast.makeText(SimpleReceiveCustomerActivity.this, "领取成功！", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }
    private void loadData(int refresh) {
        if (refresh==AutoListView.REFRESH){
            UpdateTextTask updateTextTask = new UpdateTextTask();
            updateTextTask.execute();
        }else if(refresh==AutoListView.LOAD){
            LoadTask loadTask = new LoadTask();
            loadTask.execute();
        }

    }
    class LoadTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {

            int what = 1;
            msg.what = what;
            customerDao customerdao = new customerDaoImpl();
            page=page+1;
            customerlist = customerdao.querySimpleReceiveCustomerMessage(baseClass.query_all_receive_customer+page, null);
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {

            msg.obj = customerlist;
            handler.sendMessage(msg);
            super.onPostExecute(integer);
        }
    }
    class UpdateTextTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {

            int what = 0;
            msg.what = what;
            page =1;
            customerDao customerdao = new customerDaoImpl();
            customerlist = customerdao.querySimpleReceiveCustomerMessage(baseClass.query_all_receive_customer+page, null);
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {

            msg.obj = customerlist;
            handler.sendMessage(msg);
            super.onPostExecute(integer);
        }
    }
    public void onRefresh() {
        loadData(AutoListView.REFRESH);
    }
    public  void onLoad(){
        loadData(AutoListView.LOAD);
    }

}
